package v1

import (
	"encoding/base64"

	"github.com/pkg/errors"
	"google.golang.org/protobuf/encoding/protojson"
	"google.golang.org/protobuf/proto"

	cpb "quipus/proto/gen/common"
)

func convertRowStatusToEnum(v string) cpb.RowStatus {
	return cpb.RowStatus(cpb.RowStatus_value[v])
}

func convertRowStatusToStr(rowStatus cpb.RowStatus) string {
	return cpb.RowStatus_name[int32(rowStatus)]
}

func getPageToken(limit int32, offset int32) (string, error) {
	return marshalPageToken(&cpb.PageToken{
		Limit:  int32(limit),
		Offset: int32(offset),
	})
}

func marshalPageToken(pageToken *cpb.PageToken) (string, error) {
	b, err := proto.Marshal(pageToken)
	if err != nil {
		return "", errors.Wrapf(err, "failed to marshal page token")
	}
	return base64.StdEncoding.EncodeToString(b), nil
}

func unmarshalPageToken(s string, pageToken *cpb.PageToken) error {
	// b, err := base64.StdEncoding.DecodeString(s)
	// if err != nil {
	// 	return errors.Wrapf(err, "failed to decode page token")
	// }
	b := []byte(s)

	if b[0] == '{' { // for backward compatibility
		err := protojson.Unmarshal(b, pageToken)
		if err != nil {
			return errors.Wrapf(err, "failed to unmarshal page token")
		}
		return nil
	}

	if err := proto.Unmarshal(b, pageToken); err != nil {
		return errors.Wrapf(err, "failed to unmarshal page token")
	}
	return nil
}
